package com.sws.device.config;

import jakarta.websocket.server.ServerEndpointConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * WebSocket配置类
 * 用于启用WebSocket服务器端点
 */
@Configuration
public class WebSocketConfig {
    
    private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);
    
    @Value("${spring.websocket.max-text-message-buffer-size:131072}")
    private int maxTextMessageBufferSize;
    
    @Value("${spring.websocket.max-binary-message-buffer-size:131072}")
    private int maxBinaryMessageBufferSize;
    
    @Value("${server.websocket.max-idle-timeout:3600000}")
    private long maxIdleTimeout;
    
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        ServerEndpointExporter exporter = new ServerEndpointExporter();
        log.info("WebSocket服务器端点导出器已创建");
        log.info("配置参数: 最大文本消息缓冲区大小={}, 最大二进制消息缓冲区大小={}, 最大空闲超时时间={}ms", 
                maxTextMessageBufferSize, maxBinaryMessageBufferSize, maxIdleTimeout);
        return exporter;
    }
    
    /**
     * 自定义WebSocket配置器
     * 用于设置WebSocket的全局配置
     */
    @Bean
    public CustomConfigurator customConfigurator() {
        return new CustomConfigurator(maxTextMessageBufferSize, maxBinaryMessageBufferSize, maxIdleTimeout);
    }
    
    /**
     * 自定义的WebSocket配置器
     * 用于在WebSocket连接建立时应用自定义配置
     */
    public static class CustomConfigurator extends ServerEndpointConfig.Configurator {
        private final int textBufferSize;
        private final int binaryBufferSize;
        private final long idleTimeout;
        private static final Logger log = LoggerFactory.getLogger(CustomConfigurator.class);
        
        /**
         * 默认构造函数，用于WebSocket容器实例化
         */
        public CustomConfigurator() {
            this(131072, 131072, 3600000);
        }
        
        /**
         * 带参数的构造函数，用于Spring Bean配置
         */
        public CustomConfigurator(int textBufferSize, int binaryBufferSize, long idleTimeout) {
            this.textBufferSize = textBufferSize;
            this.binaryBufferSize = binaryBufferSize;
            this.idleTimeout = idleTimeout;
            log.info("创建WebSocket配置器: 文本缓冲区大小={}, 二进制缓冲区大小={}, 空闲超时时间={}ms", 
                    textBufferSize, binaryBufferSize, idleTimeout);
        }
        
        @Override
        public void modifyHandshake(ServerEndpointConfig sec,
                                    jakarta.websocket.server.HandshakeRequest request,
                                    jakarta.websocket.HandshakeResponse response) {
            // 在握手时设置全局配置
            sec.getUserProperties().put("org.apache.tomcat.websocket.textBufferSize", textBufferSize);
            sec.getUserProperties().put("org.apache.tomcat.websocket.binaryBufferSize", binaryBufferSize);
            sec.getUserProperties().put("org.apache.tomcat.websocket.maxIdleTimeout", idleTimeout);
            
            // 启用自动Ping/Pong机制，保持连接活跃
            sec.getUserProperties().put("org.apache.tomcat.websocket.enablePingPong", true);
            
            // 记录握手信息
            String remoteAddr = request.getHeaders().get("X-Forwarded-For") != null ? 
                    request.getHeaders().get("X-Forwarded-For").get(0) : 
                    request.getHeaders().get("Origin") != null ? 
                            request.getHeaders().get("Origin").get(0) : "未知";
            
            log.debug("WebSocket握手请求: 远程地址={}, 路径={}", remoteAddr,
                    request.getRequestURI() != null ? request.getRequestURI().getPath() : "未知");
                    
            super.modifyHandshake(sec, request, response);
        }
    }
} 